package com.bac.rentmap.web.controller.osmimport;

import com.bac.rentmap.manager.BuildingManager;
import com.bac.rentmap.model.Building;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *
 * @author Ivan Holub
 */
public class ClearBuildingsController extends SimpleFormController {

    protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {

        int buildingsCount = buildingManager.getBuildingsCount();
        int maxNumber = buildingManager.getMaxNumber("minsk");

        httpServletRequest.setAttribute("buildingsSize", buildingsCount);
        httpServletRequest.setAttribute("maxNumber", maxNumber);

        ClearBuildingsCommand command = new ClearBuildingsCommand();

        return command;
    }

    private BuildingManager buildingManager;

    public void setBuildingManager(BuildingManager buildingManager) {
        this.buildingManager = buildingManager;
    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {

        ClearBuildingsCommand command = (ClearBuildingsCommand) o;

        int number = Integer.valueOf(command.getNumber());

        buildingManager.clearBuildings(number);

        int buildingsCount = buildingManager.getBuildingsCount();
        int maxNumber = buildingManager.getMaxNumber("minsk");

        httpServletRequest.setAttribute("buildingsSize", buildingsCount);
        httpServletRequest.setAttribute("maxNumber", maxNumber);

        return super.onSubmit(httpServletRequest, httpServletResponse, o, e);
    }

    protected void initBinder(HttpServletRequest httpServletRequest, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }

}
